package com.mzj.saas.mservice.property.service;

import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.property.entity.ComplainSuggestReply;
import com.mzj.saas.mservice.property.repository.ComplainSuggestReplyRepository;
import com.mzj.saas.mservice.property.vo.ComplainSuggestReplyVO;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author hikari
 * @since 2021-05-13
 */
@Service
public class ComplainSuggestReplyService {
    private static final Logger log = LoggerFactory.getLogger(ComplainSuggestReplyService.class);

    @Autowired
    private ComplainSuggestReplyRepository complainSuggestReplyRepository;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 回复列表
     *
     * @param complainSuggestId
     * @param pageNumber
     * @param pageSize
     * @param deviceType        设备类型 1 小程序  2 PC端
     * @return
     */
    public ResultBean<ApiData<ComplainSuggestReplyVO>> findByComplainSuggestId(Long complainSuggestId,
                                                                               Integer pageNumber, Integer pageSize, Integer deviceType) {
        try {
            Pageable pageable = PageRequest.of(pageNumber, pageSize);
            ApiData<ComplainSuggestReplyVO> apiData = new ApiData<>();

            if (deviceType != null && deviceType == 1) {
                // 修改消息状态
                String sql = "UPDATE saas_complain_suggest_reply SET recoil_state = 1 WHERE complain_suggest_id = ?";
                jdbcTemplate.update(sql, complainSuggestId);
            }

            Page<ComplainSuggestReply> complainSuggestReplyList =
                    complainSuggestReplyRepository.findByComplainSuggestId(complainSuggestId, pageable);

            List<ComplainSuggestReplyVO> voList = new ArrayList<>();
            for (ComplainSuggestReply complainSuggestReply : complainSuggestReplyList) {
                voList.add(convertToVO(complainSuggestReply));
            }

            apiData.setTotal(complainSuggestReplyList.getTotalElements());
            apiData.setData(voList);

            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<ComplainSuggestReplyVO> save(String accessToken, ComplainSuggestReplyVO complainSuggestReplyVO) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) return ResultBean.failedResultOfToken();

            ComplainSuggestReply complainSuggestReply = new ComplainSuggestReply();
            BeanUtils.copyProperties(complainSuggestReplyVO, complainSuggestReply);
            complainSuggestReply.setContent(complainSuggestReplyVO.getContent().getBytes());

            Long parentId = findLastReplyId(complainSuggestReplyVO.getComplainSuggestId());
            complainSuggestReply.setParentId(parentId);

            // 新增消息回复状态 0未读 1已读
            if (complainSuggestReplyVO.getType() == 1) {
                complainSuggestReply.setRecoilState(0);
            } else {
                complainSuggestReply.setRecoilState(1);
            }
            complainSuggestReply.setCreatorId(token.getId());
            complainSuggestReply.setCreateTime(new Date());

            complainSuggestReplyRepository.save(complainSuggestReply);

            ComplainSuggestReplyVO vo = convertToVO(complainSuggestReply);
            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public Long findLastReplyId(Long complainSuggestId) {
        List<ComplainSuggestReply> replies = complainSuggestReplyRepository.findByComplainSuggestId(complainSuggestId);

        if (replies == null || replies.isEmpty()) {
            return null;
        }

        return replies.get(replies.size() - 1).getId();
    }

    public ComplainSuggestReplyVO convertToVO(ComplainSuggestReply complainSuggestReply) {
        ComplainSuggestReplyVO vo = new ComplainSuggestReplyVO();
        vo.setId(complainSuggestReply.getId());
        vo.setParentId(complainSuggestReply.getParentId());
        vo.setComplainSuggestId(complainSuggestReply.getComplainSuggestId());
        vo.setType(complainSuggestReply.getType());
        vo.setTypeName(vo.getType() == 1 ? "物业回复" : "业主回复");
        vo.setContent(new String(complainSuggestReply.getContent()));
        vo.setCreatorId(complainSuggestReply.getCreatorId());
        vo.setCreateTime(complainSuggestReply.getCreateTime());

        return vo;
    }

    public ResultBean<Object> verifyReply(String accessToken, Integer type, Long complainSuggestId) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) return ResultBean.failedResultOfToken();

            Integer flag = 1;// 标识：0不可回复，1可回复
            int count = complainSuggestReplyRepository.findCountByTypeAndCSId(type, complainSuggestId);
            if (count >= 3) {
                flag = 0;
                return ResultBean.successfulResultWithMsg("回复次数不能超过三次", flag);
            }

            return ResultBean.successfulResult(flag);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


}
